package com.mrd.gtimp.business.action;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mrd.exception.SaveException;
import com.mrd.framework.config.web.json.annotation.JField;
import com.mrd.framework.config.web.json.annotation.Json;
import com.mrd.framework.ui.Jqgrid;
import com.mrd.framework.ui.filter.SearchRule;
import com.mrd.framework.ui.filter.SearchRuleOption;
import com.mrd.gtimp.business.entity.CompanyQpTemp;
import com.mrd.gtimp.business.service.CompanyQpBiz;
import com.mrd.gtimp.business.service.CompanyQpTempBiz;
import com.mrd.util.FreeMarkerUtils;
import com.mrd.util.GtimpBusinessUtil;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.annotation.Resource;

/**
 * <p> application name: gtimp <p> copyright: Copyright@2012 明睿达科技有限公司
 */

/**
 * @author yangyl
 */

@Controller
@RequestMapping("/business")
public class CompanyQpAction {
    private static final long serialVersionUID = 1L;
    private static Logger logger = Logger.getLogger(CompanyQpAction.class);

    private CompanyQpBiz companyQpBiz;
    @Resource
    private CompanyQpTempBiz companyQpTempBiz;

    /**
     * 返回前台的结果变量，格式为[[显示值，真实值],[显示值1，真实值1],...]
     */
    private String[][] results;

    @RequestMapping("/companyqp-findCompanyByCode")
    @ResponseBody
    public String[][] findCompanyByCode(@RequestParam(required = false) String k) {
        try {
            String[][] result = companyQpBiz.findCompanyCode(k);
            if (result == null || result.length == 0) {
                result = new String[1][2];
                result[0][0] = "**请新增**";
                result[0][1] = "";
            }
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 页面路径
     */
    private enum PagePath {
        frame_add_companyQP, waitAuditCompanyQpTempList, auditCompanyQpTempDetail;

        public String path() {
            return "/companyqp/" + this.name();
        }
    }

    @RequestMapping("/companyQp/frame_to_add_companyQP")
    public String frameToAddCompanyQP() {
        return PagePath.frame_add_companyQP.path();
    }

    /**
     * ajax提交临时供应商信息
     * @param temp
     *            临时供应商信息
     * @next 页面后续动作：判断提交结果，成功保存则提示用户是否需要填写另外的供应商信息。
     */
    @RequestMapping("/companyQp/j_cqpt_save")
    @ResponseBody
    public JSONObject ajaxCompanyQpTempSave(CompanyQpTemp temp, Model model) {
        JSONObject jsonObject = new JSONObject();
        try {
            companyQpTempBiz.saveCompanyQpTemp(temp);
        } catch (Exception e) {
            logger.info("保存收发货人出现异常");
            jsonObject.put("rs", 0);
            return jsonObject;
        }
        jsonObject.put("rs", 1);
        return jsonObject;
    }

    /**
     * ajax提交临时供应商信息--审批信息
     */
    @RequestMapping("/companyQp/j_cqpt_audit_save")
    @ResponseBody
    public JSONObject ajaxCompanyQpTempAudit(CompanyQpTemp temp, String pass) {
        JSONObject jsonObject = new JSONObject();
        List<String> cqpJsonList = temp.getCqps();
        List<CompanyQpTemp> temps = new ArrayList<>();
        for (String json : cqpJsonList) {
            JSONObject qpObject = JSON.parseObject(json);
            CompanyQpTemp qpTemp = JSON.toJavaObject(qpObject, CompanyQpTemp.class);
            GtimpBusinessUtil.handleNullValueCustomJPAField(qpTemp);
            temps.add(qpTemp);
        }
        try {
            companyQpTempBiz.auditCompanyQpTemps(temps, "1".equals(pass));
        } catch (Exception e) {
            if (e.getClass().isAssignableFrom(SaveException.class)) {
                jsonObject.put("errmsg", e.getMessage());
            }
            logger.info("审核收发货人信息时出现异常");
            jsonObject.put("rs", 0);
            return jsonObject;
        }
        jsonObject.put("rs", 1);
        return jsonObject;
    }

    /**
     * 前往待审核列表
     */
    @RequestMapping("/companyQp/toAuditCompanyQpTempList")
    public String toAuditCompanyQpTempList() {
        return PagePath.waitAuditCompanyQpTempList.path();
    }

    /**
     * 前往审核供应商信息
     */
    @RequestMapping("/companyQp/toAuditCompanyQpTempDetail")
    public String toAuditCompanyQpTempDetail(Model model, String ids) {
        String[] idarr = ids.split(",");
        List<String> idList = Arrays.asList(idarr);
        List<CompanyQpTemp> cqps = companyQpTempBiz.queryCompanyQpTempByIdList(idList);
        cqps.forEach(FreeMarkerUtils::prepareUseForFTL);
        model.addAttribute("cqps", cqps);
        return PagePath.auditCompanyQpTempDetail.path();
    }

    /**
     * 收发货人审核列表
     */
    @RequestMapping("/companyQp/j_list_cqpTemp")
    @ResponseBody
    @Json({@JField("id"), @JField("companyCode"), @JField("companyName"), @JField("companyCoUnite"),
            @JField("submitTime"), @JField("submitor.name"),
            @JField("submitor.belongCompanyName")})
    public Page<CompanyQpTemp> listCqpTemp(Jqgrid jqgrid, String closed) {
        if (StringUtils.isNotEmpty(closed)) {
            jqgrid.addRule(new SearchRule("closed", SearchRuleOption.eq, closed));
        }
        if (jqgrid.getOrder() == null) {// 默认排序--提交时间--逆序
            jqgrid.addOrder(Sort.Direction.DESC, "submitTime");
        }
        Page<CompanyQpTemp> cqpt = companyQpTempBiz.queryCompanyQpTempByJqgrid(jqgrid);
        return cqpt;
    }

    /**
     * 使用code查询供应商地址、电话、传真
     * @param code
     *            编码
     */
    @RequestMapping("/companyQp/query_address_phone_fax")
    @ResponseBody
    public String queryCompanyQpAddressAndPhoneAndFax(String code) {
        return companyQpBiz.queryCompanyQpAddressAndPhoneAndFax(code);
    }

    @Resource
    public void setCompanyQpBiz(CompanyQpBiz companyQpBiz) {
        this.companyQpBiz = companyQpBiz;
    }

    public String[][] getResults() {
        if (results == null || results.length == 0) {
            results = new String[1][2];
            results[0][0] = "**请新增**";
            results[0][1] = "";
        }
        return results;
    }

    @RequestMapping("/companyQp/checkExistByCompanyName")
    @ResponseBody
    public boolean checkExistByCompanyName(String companyName){
        return companyQpTempBiz.checkExistByCompanyName(companyName);
    }
}
